#include <string.h>
#include <stdlib.h>
#include "clientLoad.h"
int loadClients(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int numlines=getFileInfo(ptr_file,&maxlinelen);
	clientcount=numlines;
	clientdata=(struct ClientVars*) calloc(numlines,sizeof(struct ClientVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);//load line into buffer;
		strcpy(clientdata[i].id,strtok(buf,"/"));
		strcpy(clientdata[i].name,strtok(NULL,"/"));//subsequent tokens...
		strcpy(clientdata[i].surname,strtok(NULL,"/"));
		strcpy(clientdata[i].address,strtok(NULL,"/"));
		strcpy(clientdata[i].town,strtok(NULL,"/"));
		strcpy(clientdata[i].province,strtok(NULL,"/"));
		strcpy(clientdata[i].email,strtok(NULL,"/"));
		strcpy(clientdata[i].password,strtok(NULL,"/"));
		sscanf(strtok(NULL,"/"), "%d", &clientdata[i].balance);
	}
	fclose(ptr_file);
	return 0;
}

int writeClients(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<clientcount;i++){
		fprintf(ptr_file,"%s/%s/%s/%s/%s/%s/%s/%s/%d\n",clientdata[i].id,clientdata[i].name,clientdata[i].surname,clientdata[i].address,clientdata[i].town,clientdata[i].province,clientdata[i].email,clientdata[i].password,clientdata[i].balance);
	}
	fclose(ptr_file);
	free(clientdata);
	return 0;
}

void addClient(struct ClientVars n){
	clientdata=(struct ClientVars*) realloc(clientdata,++clientcount*sizeof(struct ClientVars));
	clientdata[clientcount-1]=n;
}

void rmClient(int index){
	for(int i=index;i<clientcount-1;i++){
		clientdata[i]=clientdata[i+1];
	}
	clientdata=(struct ClientVars*) realloc(clientdata,--clientcount*sizeof(struct ClientVars));
}
